import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import {
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
  Mesh,
  SphereGeometry,
  MeshStandardMaterial,
  AxesHelper,
  AmbientLight,
  Vector3,
  Plane,
  PointLight,
  DoubleSide,
} from "three";

let camera: PerspectiveCamera, scene: Scene, renderer: WebGLRenderer;
let control: OrbitControls;

init();
animate();

function init() {
  camera = new PerspectiveCamera(
    70,
    window.innerWidth / window.innerHeight,
    1,
    1000
  );
  scene = new Scene();
  camera.position.set(20, 20, 20);

  const clipPlanes = [
    new Plane(new Vector3(1, 0, 0), 0),
    new Plane(new Vector3(0, -1, 0), 0),
    new Plane(new Vector3(0, 0, -1), 0),
  ];

  let ambientLight = new AmbientLight("#333", 1);
  scene.add(ambientLight);
  let pointLight = new PointLight("#fff", 1);
  pointLight.position.set(-20, 20, 20);
  scene.add(pointLight);

  let axesHelper = new AxesHelper(100);
  scene.add(axesHelper);
  let sphereGeom = new SphereGeometry(10, 100, 100);
  let sphereMat = new MeshStandardMaterial({
    color: "#f00",
    // wireframe: true,
    side: DoubleSide,
    clippingPlanes: clipPlanes,
    clipIntersection: true,
  });
  let sphereMesh = new Mesh(sphereGeom, sphereMat);
  scene.add(sphereMesh);

  renderer = new WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.localClippingEnabled = true;
  document.body.appendChild(renderer.domElement);
  control = new OrbitControls(camera, renderer.domElement);
}

function animate() {
  requestAnimationFrame(animate);

  renderer.render(scene, camera);
}
